$(function(){
	genre_index.run();
});

var genre_index = {
	run: function(){
		this._init_();
		this._start_();
		this._bind_events();
	},
	
	_init_: function(){
		this.category = $("#category").val();
	},
	
	_start_: function(){
		this._list_genre();
	},
	
	_bind_events: function(){
		$("#category").change(function(){
			genre_index.category = $(this).val();
			genre_index._list_genre();
		});
		
		$("#add_genre_btn").click(function(){				
			$("#new_genre_div").admindialog('open');
		});
		
		genre_index._handle_update_delete_event();
	},
	
	_handle_update_delete_event: function(){
		//ready for dialog
		$("#new_genre_div").admindialog({
			offsetLeft: -20,
			offsetTop: -50,
			gatherData: true,
			submit: function(data){
				var url = main.contextPath + "/admin/genre/add";
				$.post(url, data, function(result){					
					$("#add_genre_table :input[type='text']").val("");
					$("#add_result_div").html(result);
				});
			},
			closeAfterSubmit: false
		});
		
		//ready for dialog
		$("#update_genre_div").admindialog({
			gatherData: true,
			submit: function(data){
				var url = main.contextPath + "/admin/genre/update";
				$.post(url, data, function(result){
					genre_index._list_genre();
				});					
			}
		});
		
		$("#genre_table  tr > td > a.update").click(function(){
			var id = $(this).attr("linkId");
			var url = main.contextPath + "/admin/genre/get/" + id;
			$.get(url, function(result){
				$("#update_content_div").html(result);		
				$("#update_genre_div").dialog('open');
			});
		});
		
		$("#genre_table  tr > td > a.delete").click(function(){
			var checked = window.confirm("Are you sure ?");
			if(checked){
				var id = $(this).attr("linkId");
				var url = main.contextPath + "/admin/genre/delete/" + id;
				$.get(url, function(result){
					alert(result);
					genre_index._list_genre();
				});
			}				
		});
	},
	
	_list_genre: function(){
		var url = main.contextPath + "/admin/genre/list?category=" + this.category;
		$.get(url, function(result){
			$("#genre_list").html(result);
			//重新绑定事件
			genre_index._handle_update_delete_event();
		});
	}
};